package org.sky.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.log4j.Logger;
import org.sky.base.PageView;
import org.sky.model.*;
import org.sky.service.*;
import org.sky.util.ChangeTime;
import org.sky.vo.RoomUsedVO;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 12-11-3
 * Time: 下午7:18
 * To change this template use File | Settings | File Templates.
 */


@Component("roomUsed")
@Scope("prototype")
public class RoomUsedAction extends MyActionSupport implements ModelDriven<RoomUsedVO> {

    private RoomUsedVO roomUsedVO = new RoomUsedVO();
    private RoomUsedService roomUsedService;
    private RoomService roomService;
    private BookingService bookingService;
    private MealService mealService;
    private PersonService personService;
    private RoomUsed roomUsed = new RoomUsed();
    //当前登录用户
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    private final String username = userDetails.getUsername();

    private final static Logger logger = Logger.getLogger(RoomUsedAction.class);

    public String AllRoom() {
        /** 每页显示的结果数 **/
        int maxResult = 6;
        /** 封装的页面数据 **/
        PageView<Person> pageView = new PageView<Person>(maxResult,
                roomUsedVO.getPage());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
                .getMaxResult());// 开始索引
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("roomId", "desc");
        orderBy.put("good", "desc");
        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        if ("true".equals(roomUsedVO.getQuery())) {
            if (roomUsedVO.getRoomId() != 0) {
                jpql.append(" and o.roomId = ?").append((params.size() + 1));
                params.add(roomUsedVO.getRoomId());
            }
            if (!"".equals(roomUsedVO.isGood())) {
                jpql.append(" and o.good = ?").append((params.size() + 1));
                params.add("%" + roomUsedVO.isGood() + "%");
            }
            if (roomUsedVO.getRoomStyle() != null && !"".equals(roomUsedVO.getRoomStyle())) {
                jpql.append(" and o.roomStyle = ?").append((params.size() + 1));
                params.add(roomUsedVO.getRoomStyle());
            }
            if (roomUsedVO.getBeginSize() > 0) {
                jpql.append(" and o.size >= ?").append((params.size() + 1));
                params.add(roomUsedVO.getBeginSize());
            }
            if (roomUsedVO.getEndSize() > 0) {
                jpql.append(" and o.size <= ?").append((params.size() + 1));
                params.add(roomUsedVO.getEndSize());
            }

            pageView.setQueryResult(roomService.getScrollData(Room.class, firstIndex, maxResult, jpql.toString(),
                    params.toArray(), orderBy));
            roomUsedVO.setQuery("true");
        } else {
            roomUsedVO.setUsingRooms(roomService.showTheRoom());
            pageView.setQueryResult(roomService.getScrollData(Room.class, firstIndex, maxResult));
        }
        roomUsedVO.setPageView(pageView);
        view = "/page/roomUsed/roomlist.jsp";
        return VIEW;
    }


    //查找订单
    @Override
    public String execute() throws Exception {
        Booking order = bookingService.findOrderByOrderId(roomUsedVO.getOrderId());
        if (order == null) {
            roomUsedVO.setResultMessage("<script>alert('无法找到改订单！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
            // roomUsedVO.setResultMessage("订单号为：" + roomUsedVO.getOrderId() + " 的订单不存在！请核对信息！");
            return ERROR;
        }
        if (order.getState() == State.CANCEL) {
            roomUsedVO.setResultMessage("<script>alert('订单已取消！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
            // roomUsedVO.setResultMessage("订单号为：" + roomUsedVO.getOrderId() + " 的订单已经取消预约！请核对信息！");
            return ERROR;
        }

        roomUsedVO.setOrder(order);
        if (roomUsedVO.getFlag() == 1) {
            if (order.getState() != State.AUDIT) {
                if (order.getState() == State.SUCCESS)
                    roomUsedVO.setResultMessage("<script>alert('订单：" + order.getOrderId() + " 已经安排房间！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
                else
                    roomUsedVO.setResultMessage("<script>alert('订单：" + order.getOrderId() + " 未审核或已经取消！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
                return ERROR;
            }
            view = "/page/roomUsed/arrangeRoom.jsp";
            return VIEW;
        }
        return SUCCESS;
    }

    //安排房间
    public String arrangeRoom() {
        if (roomUsedVO.getSingerNum() == 0) {
            roomUsedVO.setResultMessage("<script>alert('请输入实际唱k人数！');location.href='RoomUsed.action?flag=1&orderId=" + roomUsedVO.getOrderId() + "';</script>");
            // roomUsedVO.setResultMessage("请输入实际唱k人数!");
            return ERROR;
        }
        Booking order = bookingService.findOrderByOrderId(roomUsedVO.getOrderId());
        if (order == null) {
            roomUsedVO.setResultMessage("<script>alert('订单：" + order.getOrderId() + " 未找到！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
            // roomUsedVO.setResultMessage("订单：" + order.getOrderId() + " 未找到！");
            return ERROR;
        }

        List<Room> rooms = roomService.arrangeRoom(roomUsedVO.getOrderId(), roomUsedVO.getSingerNum());
        if (rooms.size() <= 0) {
            roomUsedVO.setResultMessage("<script>alert('没有合适的房间！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
            //  roomUsedVO.setResultMessage("没有合适的房间!");
            return ERROR;
        }
        List<Meal> meals = mealService.findMealsFromTime(Time.valueOf(ChangeTime.formatTime2(ChangeTime.parseDate(ChangeTime.getCurrentDate()))));
        roomUsedVO.setMeals(meals);
        roomUsedVO.setRooms(rooms);
        roomUsedVO.setOrderId(roomUsedVO.getOrderId());
        roomUsedVO.setOrder(order);

        if (roomUsedVO.getFlag() == 1) {
            Room room = roomService.find(Room.class, roomUsedVO.getRoomId());
            Meal meal = mealService.find(Meal.class, roomUsedVO.getMeal());
            if (room == null || meal == null) {
                roomUsedVO.setResultMessage("<script>alert('安排房间失败！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
                // roomUsedVO.setResultMessage("安排房间失败!");
                return ERROR;
            }
            roomUsed = copyDefaultInfo(roomUsed, roomUsedVO);
            order.setState(State.SUCCESS);
            try {
                roomService.save(roomUsed);
                bookingService.update(order);
            } catch (Exception e) {
                e.printStackTrace();
                roomUsedVO.setResultMessage("<script>alert('数据库数据异常！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
                //  roomUsedVO.setResultMessage("数据库数据异常!");
                logger.error(e);
                return ERROR;
            }
            roomUsedVO.setResultMessage("<script>alert('房间安排成功！');location.href='/page/roomUsed/arrangeRoom.jsp';</script>");
            // roomUsedVO.setResultMessage("房间安排成功！房间为：" + room.getRoomId() + "! 使用的套餐为：" + meal.getMealName() + "(" + meal.getHoliday() + ")");
            logger.trace("Staff:" + username + " Order:" + roomUsed.getBooking().getOrderId() + " Room：" + room.getRoomId() + " Using meal：" + meal.getMealName() + "(" + meal.getHoliday() + ")");
            return SUCCESS;
        }

        view = "/page/roomUsed/arrangeRoom.jsp";
        return VIEW;
    }

    //计算房费
    public String calPrice() {
        roomUsed = roomUsedService.findRoomUsedByRoomId(roomUsedVO.getRoomId());
        if (roomUsed == null) {
            roomUsedVO.setResultMessage("<script>alert('房间并未使用！');location.href='/page/roomUsed/calPrice.jsp';</script>");
            // roomUsedVO.setResultMessage("房间：" + roomUsedVO.getRoomId() + " 并未使用！");
            return ERROR;
        }
        double price = roomUsedService.totalMoney(roomUsedVO.getRoomId());
        if (price != 0.0d) {
            roomUsedVO.setResultMessage("<script>alert('房间：" + roomUsedVO.getRoomId() + " 房费计算成功！" + "房费为：" + price + "元。请付款！');</script>");
            // roomUsedVO.setResultMessage("房间：" + roomUsedVO.getRoomId() + " 房费计算成功！" + "房费为：" + price + "元。请付款！");
            logger.trace("Room：" + roomUsedVO.getRoomId() + " cal price(" + price + ")success！");
            view = "/page/roomUsed/payForOrder.jsp";
            return VIEW;
        }
        roomUsedVO.setResultMessage("<script>alert('房费计算失败！');location.href='/page/roomUsed/calPrice.jsp';</script>");
        //roomUsedVO.setResultMessage("房间：" + roomUsedVO.getRoomId() + " 房费计算失败！");
        return ERROR;
    }

    //付款
    public String payForOrder() {
        roomUsed = roomUsedService.findRoomUsedByRoomId(roomUsedVO.getRoomId());

        if (roomUsed == null) {
            roomUsedVO.setResultMessage("<script>alert('房间并未使用！');location.href='/page/roomUsed/payForOrder.jsp';</script>");
            //  roomUsedVO.setResultMessage("房间：" + roomUsedVO.getRoomId() + " 并未使用！");
            return ERROR;
        }
        roomUsed.setPay(PayForOrder.PAY);
        roomUsed.setCashier(username);
        Booking booking = bookingService.findOrderByOrderId(roomUsed.getBooking().getOrderId());
        Person person = personService.find(Person.class, booking.getUserId().getId());
        if ((person.getLevel() + 1) % 3 == 0)
            person.setLevel(person.getLevel() + 1);

        try {
            roomUsedService.update(roomUsed);
            personService.update(person);
        } catch (Exception e) {
            e.printStackTrace();
            roomUsedVO.setResultMessage("<script>alert('付款失败！');location.href='/page/roomUsed/payForOrder.jsp';</script>");
            //roomUsedVO.setResultMessage("付款失败！");
            return ERROR;
        }
        roomUsedVO.setResultMessage("<script>alert('成功付款！欢迎下次光临！');location.href='/page/roomUsed/payForOrder.jsp';</script>");
        // roomUsedVO.setResultMessage("成功付款！欢迎下次光临！");
        return SUCCESS;
    }

    //设置额外收费
    public String extraMoney() {
        roomUsed = roomUsedService.findRoomUsedByRoomId(roomUsedVO.getRoomId());
        if (roomUsed == null) {
            roomUsedVO.setResultMessage("<script>alert('房间并未使用！');location.href='/page/roomUsed/payForOrder.jsp';</script>");
            //  roomUsedVO.setResultMessage("房间：" + roomUsedVO.getRoomId() + " 并未使用！");
            return ERROR;
        }
        roomUsed.setExtraMoney(roomUsedVO.getExtraMoney());
        roomUsedService.update(roomUsed);
        roomUsedVO.setResultMessage("<script>alert('房间：" + roomUsedVO.getRoomId() + " 设置额外收费成功！" + "额外收费为：" + roomUsedVO.getExtraMoney() + "！');location.href='/page/roomUsed/payForOrder.jsp';</script>");
        //roomUsedVO.setResultMessage("房间：" + roomUsedVO.getRoomId() + " 设置额外收费成功！" + "额外收费为：" + roomUsedVO.getExtraMoney());
        logger.trace("Room:" + roomUsedVO.getRoomId() + " ExtraMoney:" + roomUsedVO.getExtraMoney());
        return SUCCESS;
    }

    //营业额
    public String revenue() {
        List<RoomUsed> roomUses = roomUsedService.revenueInTimes(setDate(roomUsedVO.getStartTime()),
                setDate(roomUsedVO.getEndTime()));
        if (roomUses.size() <= 0) {
            roomUsedVO.setResultMessage("<script>alert('未有营业额进账！');location.href='/page/roomUsed/revenue.jsp';</script>");
          //  roomUsedVO.setResultMessage("从 " + roomUsedVO.getStartTime() + " 到 " + roomUsedVO.getEndTime() + " 时间内，未有营业额进账！");
            return ERROR;
        }
        /*计算营业额*/
        double money = 0.0d;
        List<Double> roomPrice = new ArrayList<java.lang.Double>();
        for (int i = 0; i < roomUses.size(); i++) {
            RoomUsed ru = roomUses.get(i);
            money = money + roomUses.get(i).getMoney();
        }
        DecimalFormat df = new DecimalFormat("0.00");      //设置小数点后两位
        roomUsedVO.setMoney(Double.parseDouble(df.format(money)));
        roomUsedVO.setMoney(money);
        roomUsedVO.setRoomUses(roomUses);
        view = "/page/roomUsed/revenue.jsp";
        return VIEW;
    }

    @Override
    public RoomUsedVO getModel() {
        return roomUsedVO;
    }

    @Resource(name = "roomUsedServiceImpl")
    public void setRoomUsedService(RoomUsedService roomUsedService) {
        this.roomUsedService = roomUsedService;
    }

    @Resource(name = "bookingServiceImpl")
    public void setBookingService(BookingService bookingService) {
        this.bookingService = bookingService;
    }

    @Resource(name = "mealServiceImpl")
    public void setMealService(MealService mealService) {
        this.mealService = mealService;
    }

    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    @Resource(name = "roomServiceImpl")
    public void setRoomService(RoomService roomService) {
        this.roomService = roomService;
    }


    private RoomUsed copyDefaultInfo(RoomUsed target, RoomUsedVO roomUsedVO) {
        ChangeTime changeTime = new ChangeTime();
        Date currentDate = changeTime.parseDate(changeTime.getCurrentDate());
        target.setCreateTime(currentDate);
        target.setStartTime(currentDate);
        target.setBooking(bookingService.findOrderByOrderId(roomUsedVO.getOrderId()));
        target.setPay(PayForOrder.NOT_PAY);
        target.setMeal(mealService.find(Meal.class, roomUsedVO.getMeal()));
        target.setRoom(roomService.find(Room.class, roomUsedVO.getRoomId()));
        target.setSingerNum(roomUsedVO.getSingerNum());
        return target;
    }

    private Date setDate(String time) {
        return ChangeTime.parseDate(time + ":00");
    }
}
